package parser;

import java.io.PrintWriter;

import lexer.TokenType;

/**
 * Implements parsing and store of a LOGO IF-ELSE statement into an appropriate
 * data structure Grammar: IF (expr) THEN (statements) ELSE (statements) ENDIF
 */
public class LogoIfStatement extends LogoStatement {

	LogoExpression condition;
	LogoStatements trueBody;
	LogoStatements falseBody;

	/**
	 * Parsers an IF statement starting from the current Token in the
	 * TokenIterator
	 * 
	 * @param TokenIterator
	 * @throws LogoParseException
	 */
	public LogoIfStatement(TokenIterator it) throws LogoParseException {
		parseTokens(it);
	}

	private void parseTokens(TokenIterator it) throws LogoParseException {
		if (!it.hasNext()) {
			throw new LogoParseException("Unexpectedly reached end of program");
		}

		it.ExpectedNext(TokenType.IF);
		condition = LogoExpressionParser.parseExpression(it);

		it.ExpectedNext(TokenType.THEN);

		// parse the statements executed if true
		trueBody = new LogoStatements(it, TokenType.ELSE, false);

		it.ExpectedNext(TokenType.ELSE);

		// Parse the false body of code
		falseBody = new LogoStatements(it, TokenType.ENDIF, false);

		it.ExpectedNext(TokenType.ENDIF);
	}

	@Override
	public void resolveIdentifiers(LogoScope scope) throws LogoParseException {
		trueBody.resolveIdentifiers(scope);
		falseBody.resolveIdentifiers(scope);
		condition.resolveIdentifiers(scope);
	}

	/**
	 * Example output: LEVEL 1 eq { 5 forward } { 90 left } ifelse
	 */
	@Override
	public void generatePostScriptCode(PrintWriter stream) {
		condition.generatePostScriptCode(stream);
		stream.println("{");
		trueBody.generatePostScriptCode(stream);
		stream.println("} {");
		falseBody.generatePostScriptCode(stream);
		stream.println("} ifelse");
	}
}
